package controller

import (
	"danmu/common"
	"danmu/dto"
	"danmu/model"
	"danmu/response"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

//评论
func Comment(ctx *gin.Context){
	DB :=common.GetDB()
	var requestComment = model.Comment{}
	err := ctx.Bind(&requestComment)
	if err != nil{
		response.Response(ctx,http.StatusBadRequest,400,nil,"请求错误")
		return
	}
	//评论或回复
	text := requestComment.Text
	vid := requestComment.Vid
	uid,_ := ctx.Get("id")
	//回复的评论id，如果不为空就是回复
	lastId := requestComment.LastId
	replyUid := requestComment.ReplyUid
	replyName := requestComment.ReplyName
	if vid ==0 || uid ==0{
		response.Fail(ctx,nil,"评论失败")
		return
	}
	var newComment = model.Comment{}
	if lastId == 0{
		newComment.Uid = uid.(uint)
		newComment.Vid = vid
		newComment.Text = text
	}else{
		newComment.Uid = uid.(uint)
		newComment.Vid = vid
		newComment.Text = text
		newComment.LastId = lastId
		newComment.ReplyName = replyName
		newComment.ReplyUid = replyUid
	}

	DB.Create(&newComment)
	response.Success(ctx,nil,"评论成功")
}

//获取评论
func GetComment(ctx *gin.Context){
	//增加分页
	DB :=common.GetDB()
	var comment []model.Comment
	vid := ctx.DefaultQuery("vid", "0")
	if vid == "0" {
		response.Fail(ctx,nil,"视频不存在")
		return
	}
	//获取分页信息
	page, _ := strconv.Atoi(ctx.Query("page"))
	pageSize, _  := strconv.Atoi(ctx.Query("page_size"))
	if page > 0 && pageSize > 0{
		//记录总数
		var totalSize int
		//分页
		DB = DB.Limit(pageSize).Offset((page - 1) * pageSize)
		//评论
		DB.Where("vid = ? AND last_id = ?", vid, "0").Preload("Author").Find(&comment).Count(&totalSize)
		//如果想获取的个数小于存在的个数，则只返回存在的内容
		if pageSize > len(comment){
			response.Success(ctx,gin.H{"count":totalSize,"data":dto.ToCommentDto(comment,len(comment))},"获取成功")
		}else{
			response.Success(ctx,gin.H{"count":totalSize,"data":dto.ToCommentDto(comment,pageSize)},"获取成功")
		}
	}else{
		response.Fail(ctx,nil,"获取失败")
		return
	}
}

//删除评论
func DeleteComment(ctx *gin.Context)  {
	DB :=common.GetDB()
	//从参数中获取id
	var requestComment = model.Comment{}
	var comment = model.Comment{}
	err := ctx.Bind(&requestComment)
	if err != nil{
		response.Response(ctx,http.StatusBadRequest,400,nil,"请求错误")
		return
	}
	id := requestComment.ID
	//根据id查找评论
	DB.First(&comment, id)
	if comment.ID == 0 {
		response.Fail(ctx,nil,"评论不存在")
		return
	}
	//验证作者获取ID
	uid,_ :=ctx.Get("id")
	if comment.Uid != uid {
		ctx.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"权限不足"})
		return
	}
	DB.Delete(&comment)
	response.Success(ctx,nil,"删除成功")
}
